package org.raycloud;

import java.io.IOException;
import java.util.concurrent.*;


//
//        线程池类为 java.util.concurrent.ThreadPoolExecutor，常用构造方法为：
//        ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)
//
//        corePoolSize： 线程池维护线程的最少数量
//        maximumPoolSize：线程池维护线程的最大数量
//        keepAliveTime： 线程池维护线程所允许的空闲时间
//        unit： 线程池维护线程所允许的空闲时间的单位
//        workQueue： 线程池所使用的缓冲队列
//        handler： 线程池对拒绝任务的处理策略
public class newFixedThreadPoolTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        //ExecutorService service = Executors.newFixedThreadPool(2);

//        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(3);
//        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 1, TimeUnit.HOURS, queue, new ThreadPoolExecutor.CallerRunsPolicy());


        //使用直接提交策略，也即SynchronousQueue。
        ThreadPoolExecutor executor =new ThreadPoolExecutor(
                3, 3, 30, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>(),
                new ThreadPoolExecutor.CallerRunsPolicy());


        for (int i = 0; i < 6; i++) {
            final int index = i;
            System.out.println("task: " + (i + 1));
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    System.out.println("thread start" + index);
                    try {
                        Thread.sleep(Long.MAX_VALUE);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("thread end" + index);
                }
            };
            //service.execute(run);
            executor.execute(run);
        }

    }
}